import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//import java.awt.MediaTracker;

public class NetworkImageDisplay3 {

    public static void main(String[] args) {
        String imageUrl = "https://cst.qdu.edu.cn/__local/1/67/3F/CD80048F2C2EB26F9D8B891FDF2_078E7E73_D4B0.png"; // Replace with your image URL

        ImageIcon icon = ImageLoader.loadImage(imageUrl);

        if (icon != null) {
            ImageDisplay.showImage(icon, "Network Image Display");
        } else {
            System.out.println("Failed to load image.");
        }
    }
}

class ImageLoader {
    public static ImageIcon loadImage(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 0) {
                contentLength = 1024; // Default buffer size if content length is unknown
            }
            System.out.println("contentlen: " + contentLength);
            //==================================================================
            InputStream is = connection.getInputStream();
            //用字节缓冲流处理图片
            
            //==================================================================
            //ImageIcon icon = new ImageIcon(imageData);

            /*Check if the image is completely loaded
            MediaTracker tracker = new MediaTracker(new JFrame());
            tracker.addImage(icon.getImage(), 0);
            tracker.waitForID(0);
            if (tracker.isErrorID(0)) {
                return null;
            }*/

            return icon;
        } catch (Exception e) {
            System.err.println("Error loading image: " + e.getMessage());
            return null;
        }
    }
}

class ImageDisplay {
    public static void showImage(ImageIcon icon, String title) {
        JFrame frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel label = new JLabel(icon);
        frame.getContentPane().add(label);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}